const ua = navigator.userAgent.toLowerCase();
const isIos =
  /(ios|ipad|iphone)/.test(ua) || (ua.indexOf('macintosh') > -1 && 'ontouchend' in document);
const isAndroid = /android/.test(ua);
const isWeixin = /micromessenger/.test(ua);
// 请求有个空格
const isQQ = / qq/.test(ua);
const isWeibo = /weibo/.test(ua);

const jump = (binding) => {
  const toTarget = encodeURIComponent(binding.value.to);
  if (isAndroid && isWeixin) {
    window.location.href = `https://a.app.qq.com/o/simple.jsp?pkgname=com.movtile.jimu&android_scheme=${binding.value.to}`;
    return;
  }

  if ((isAndroid && !isWeixin) || isQQ) {
    const a = document.createElement('a');
    a.id = `hide_scheme_${Math.ceil(Math.random() * 10e3)}`;
    a.setAttribute('href', binding.value.to);
    document.body.appendChild(a);
    a.click();
    a.remove();
    setTimeout(() => {
      window.location.href = `https://ul.movtile.com/wxjump.html?scheme=${toTarget}`;
    }, 200);
  } else {
    window.location.href = `https://ul.movtile.com/wxjump.html?scheme=${toTarget}`;
  }
};

export default {
  install(Vue) {
    Vue.directive('app-jump', {
      inserted(el, binding) {
        if (isIos && el.getAttribute('youmeng')) {
          if (!el.id) {
            return console.error('使用app-jump, 请给dom设置一个唯一的ID值');
          }
          ULink([
            {
              id: 'usr106qi5aora98f', // 后台生成的裂变活动LinkID
              data: {
                id: el.id,
                // 传递的自定义动态参数
                ...(binding.value.params || {}),
              },
              selector: `#${el.id}`,
              auto: false,
              lazy: true,
              useOpenInBrowerTips: 'default',
              proxyOpenDownload: function (defaultAction, LinkInstance) {
                if (LinkInstance.solution.type === 'scheme') {
                  // qq或者微信环境特殊处理下
                  if (ULink.isWechat || ULink.isQQ) {
                    // 在qq或者微信环境执行内置逻辑，具体内置逻辑为:当设置了useOpenInBrowerTips字段时，qq&&微信&&scheme时，启用蒙层提示去浏览器打开
                    defaultAction();
                  } else {
                    window.location.href = LinkInstance.solution.downloadUrl;
                  }
                } else if (LinkInstance.solution.type === 'universalLink') {
                  // universalLink 唤起应当由服务端提供一个带重定向到appstore的universallink地址。因此，此处不应写逻辑，友盟会在近期上线universalLink 重定向功能。
                }
              },
            },
          ]);
        } else {
          el.addEventListener('click', () => jump(binding));
        }
      },
    });
  },
};
